package com.j2eefast.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.j2eefast.common.core.utils.RedisUtil;
import com.j2eefast.web.common.BaseUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录服务
 */
@Service
public class JumucLoginService {

    @Autowired
    private RedisUtil cacheUtil;

    private final static String USERNAME = "zhaoxiaoming";
    private final static String PASSWORD = "zxm123";

    private String TOKEN_KEY = "JUMUC_TOKEN";

    public String getToken(){
        String token = cacheUtil.get(TOKEN_KEY);
        if(StrUtil.isEmpty(token)){
            doLogin();
        }

        return cacheUtil.get(TOKEN_KEY);
    }

    private void doLogin() {
        String url = BaseUrl.JUMUC_LOGIN_URL;
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("userName",USERNAME);
        paramMap.put("password",PASSWORD);
        String result = HttpRequest.post(url)
                .header("Content-Type","application/json;charset=UTF-8")
                .header("Authorization","123456")
                .body(JSONUtil.toJsonStr(paramMap))
                .execute()
                .body();

        JSONObject data = JSONUtil.parseObj(result);
        cacheUtil.set(TOKEN_KEY,data.getJSONObject("data").getStr("token"));

    }
}
